const WXAPI = require('../wxapi/main')

/**
 * type: order 支付订单 recharge 充值 paybill 优惠买单
 * data: 扩展数据对象，用于保存参数
 */
function wxpay(type, money, orderId, redirectUrl, data) {
  let remark = "在线充值";
  let nextAction = {
    type: type,
    id: orderId
  };
  WXAPI.wxpay({
    money: money,
    nextAction: JSON.stringify(nextAction)
  }).then(function (res) {
    if (res.type == 'success') {
      let dd = res.resultData.row;
      // 发起支付
      wx.requestPayment({
        timeStamp: dd.timeStamp,
        nonceStr: dd.nonceStr,
        package: 'prepay_id=' + dd.prepayId,
        signType: 'MD5',
        paySign: dd.sign,
        fail: function (aaa) {
          wx.showToast({
            title: '支付失败:' + aaa
          })
        },
        success: function () {
          // // 保存 formid
          // WXAPI.addTempleMsgFormid({
          //   token: wx.getStorageSync('token'),
          //   type: 'pay',
          //   formId: dd.prepayId
          // })
          // 提示支付成功
          wx.showToast({
            title: '支付成功'
          })
          wx.reLaunch({
            url: redirectUrl
          });
        }
      })
    } else {
      wx.showModal({
        title: '出错了',
        content: res.code + ':' + res.msg + ':' + res.data,
        showCancel: false,
        success: function (res) {

        }
      })
    }
  })
}

module.exports = {
  wxpay: wxpay
}